package com.wmd.core.operation;

import com.wmd.core.operation.ExcelOperation.*;
import com.wmd.core.operation.ExcelOperation.CellStyle;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import java.io.*;
import java.util.List;

/**
 * 类说明
 *
 * @author yincheng lu
 * @time 2019年3月12日上午11:27:41
 * @Description
 */
public class ExportExcelFile {
    public static final String HSSF="HSSF";
    public static final String XSSF="XSSF";

    public static Workbook excel(ExcelOperation excelOperation) {
        // 创建Excel文件
        return excel(excelOperation, HSSF);
    }

    public static Workbook excel(ExcelOperation excelOperation,String book_type) {
        // 创建Excel文件
        Workbook workbook =HSSF.equals(book_type)? new HSSFWorkbook():new XSSFWorkbook();
        return excel(excelOperation, workbook);
    }
    public static Workbook excelMutipartSheet(List<ExcelOperation> excelOperations) {
        // 创建Excel文件
        return excelMutipartSheet(excelOperations,HSSF);
    }
    public static Workbook excelMutipartSheet(List<ExcelOperation> excelOperations,String book_type) {
        // 创建Excel文件
        Workbook workbook =HSSF.equals(book_type)? new HSSFWorkbook():new XSSFWorkbook();
        for (int i = 0; i < excelOperations.size(); i++) {
            excel(excelOperations.get(i), workbook);
        }
        return workbook;
    }

    public static Workbook excel(ExcelOperation excelOperation, Workbook workbook) {

        Sheet sheet = workbook.createSheet(excelOperation.getSheetName());
        String[][] data = excelOperation.getAllData();
        for (int i = 0; i < data.length; i++) {
            Row row = sheet.createRow(i);
            for (int j = 0; j < data[0].length; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(data[i][j]);
            }
        }
        List<CellStyle> cellStyles = excelOperation.getCellStyles();
        for (int i = 0; i < cellStyles.size(); i++) {
            CellStyle mycellstyle = cellStyles.get(i);
            // HSSFCellStyle cellStyle = workbook.createCellStyle(); // 新建单元格样式
            org.apache.poi.ss.usermodel.CellStyle cellStyle = myCellStyleToHSS(workbook, sheet, mycellstyle);
            sheet.getRow(mycellstyle.getRowIndex()).getCell(mycellstyle.getColumnIndex()).setCellStyle(cellStyle);

        }
        List<RowStyle> rowStyles = excelOperation.getRowStyles();
        for (int i = 0; i < rowStyles.size(); i++) {
            RowStyle rowStyle = rowStyles.get(i);

            CellStyle mycellstyle = rowStyle.getCellStyle();
            org.apache.poi.ss.usermodel.CellStyle hssfCellStyle = myCellStyleToHSS(workbook, sheet, mycellstyle);

            int endIndex = rowStyle.isMuti() ? rowStyle.getRowEndIndex() : rowStyle.getRowIndex();
            for (int j = rowStyle.getRowIndex(); j <= endIndex; j++) {
                Row row = sheet.getRow(j);
                //poi bug 此处设置行样式无效
//				row.setRowStyle(hssfCellStyle);
                for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
                    Cell cell = row.getCell(k);
                    if (cell != null) {
                        cell.setCellStyle(hssfCellStyle);
                    }
                }
            }
        }

        //添加合并单元格
        excelOperation.getMergedRegions().forEach(m->{
              CellRangeAddress region1 = new CellRangeAddress(m.rowIndex, m.endRowIndex,
                            m.columnIndex, m.endColumnIndex); // 参数1：起始行 参数2：终止行 参数3：起始列
                    // 参数4：终止列
                    sheet.addMergedRegion(region1);
        });
        //添加图片
        if(excelOperation.getPictures().size()>0){
            Drawing<?> patriarch = sheet.createDrawingPatriarch();
            CreationHelper helper = workbook.getCreationHelper();
            excelOperation.getPictures().forEach(p->{
                ClientAnchor anchor = helper.createClientAnchor();
                //二维码坐标设置
                anchor.setRow1(p.rowIndex);
                anchor.setCol1(p.columnIndex);
                anchor.setRow2(p.endRowIndex>p.rowIndex?p.endRowIndex:p.rowIndex+1);
                anchor.setCol2(p.endColumnIndex>p.columnIndex?p.endColumnIndex:p.columnIndex+1);
                Picture pict = patriarch.createPicture(anchor, workbook.addPicture(p.data, XSSFWorkbook.PICTURE_TYPE_JPEG));
            });
        }

        if(data!=null&&data[0].length>0){
			for (int k = 0; k < data[0].length; k++) {
				sheet.autoSizeColumn(k, true);
			}
		}
        return workbook;
    }

    public static org.apache.poi.ss.usermodel.CellStyle myCellStyleToHSS(Workbook workbook, Sheet sheet,
                                                 CellStyle mycellstyle) {
        org.apache.poi.ss.usermodel.CellStyle cellStyle = workbook.createCellStyle(); // 新建单元格样式
        List<StyleType> types = mycellstyle.getStypeTypes();

        for (int j = 0; j < types.size(); j++) {
            switch (types.get(j)) {
                case BORDER:
                    cellStyle.setBorderBottom(mycellstyle.getBorderBottom()); // 下边框
                    cellStyle.setBorderLeft(mycellstyle.getBorderLeft());// 左边框
                    cellStyle.setBorderTop(mycellstyle.getBorderTop());// 上边框
                    cellStyle.setBorderRight(mycellstyle.getBorderRight());// 右边框
                    break;
                case ALIGNMENT:
                    cellStyle.setAlignment(mycellstyle.getAlignment()); // 居中
                    cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                    break;
                case FONT:
                    Font font2 = workbook.createFont();
                    font2.setFontName(mycellstyle.getFontName());
                    font2.setBold(mycellstyle.isBoldWeight());// 粗体显示
                    font2.setFontHeightInPoints(mycellstyle.getFontHeightPoints()); // 字体大小
                    font2.setColor(mycellstyle.getFontColor());
                    cellStyle.setFont(font2);// 选择需要用到的字体格式
                    break;
//                case MERGED_REGION:
//                    CellRangeAddress region1 = new CellRangeAddress(mycellstyle.getRowIndex(), mycellstyle.getEndRowIndex(),
//                            mycellstyle.getColumnIndex(), mycellstyle.getEndColumnIndex()); // 参数1：起始行 参数2：终止行 参数3：起始列
//                    // 参数4：终止列
//                    sheet.addMergedRegion(region1);
//                    break;
                case FILL_COLOR:
                    cellStyle.setFillForegroundColor(mycellstyle.getFillForeGroundColor());// 设置背景色
                    cellStyle.setFillPattern(mycellstyle.getFillPattern());
                    break;
//                case COLUMN_WIDTH:
//                    if (isRowStyle) {
//                        Row row = sheet.getRow(sheet.getFirstRowNum());
//                        for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
//                            sheet.autoSizeColumn(k, true);
//                        }
//                    } else {
////					sheet.getRow(mycellstyle.getRowIndex()).setHeightInPoints(30);
//                        sheet.autoSizeColumn(mycellstyle.getColumnIndex(), true);
//                    }
                default:
                    break;
            }
        }
        return cellStyle;
    }

    public static boolean toFile(String path, Workbook workbook) {
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(path);
            workbook.write(fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public static boolean toFile(File file, Workbook workbook) {
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(file);
            workbook.write(fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
